package Threaddemo.thread_0910;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;

    private long time;

    public MyTimerTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> priorityQueue = new PriorityQueue<>();
    private Object locker = new Object();
    public void shcedule (Runnable runnable, long delay) {
        synchronized (locker) {
            if (delay < 0) {
                System.out.println("delay不符合要求");
                return;
            }
            priorityQueue.offer(new MyTimerTask(runnable, delay + System.currentTimeMillis()));
            locker.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (priorityQueue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask timerTask = priorityQueue.peek();
                        if (timerTask.getTime() >= System.currentTimeMillis()) {
                            timerTask.getRunnable().run();
                            priorityQueue.poll();    //忘记加删除
                        } else {
                                locker.wait(timerTask.getTime() - System.currentTimeMillis());
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }
}

public class demo3_0516 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.shcedule(()->{
            System.out.println("1000");
        },1000);
        timer.shcedule(()->{
            System.out.println("2000");
        },2000);
        timer.shcedule(()->{
            System.out.println("3000");
        },3000);
    }
}
